package com.github.caijinglong

import com.github.caijinglong.ext.println
import com.github.caijinglong.handler.CardHandler
import com.github.caijinglong.handler.GoldHandler
import com.github.caijinglong.handler.HealthHandler
import com.github.caijinglong.handler.RelicsHandler
import org.json.JSONObject
import java.io.FileOutputStream

fun main(args: Array<String>) {
    handleRelics()
//    handleGood(1500)
//    upgradeCard()
    maxHealth()
}

fun maxHealth(type: SavedDataType = SavedDataType.ZS) {
    val handler = HealthHandler()
    handler.bind(type.getGetter())
    handler.maxHealth()
    handler.save(type.srcPath)
}

fun upgradeCard(type: SavedDataType = SavedDataType.ZS) {
    val handler = CardHandler()
    handler.bind(type.getGetter())
    handler.upgrade()
    handler.save(type.srcPath)
}

fun handleGood(gold: Int, type: SavedDataType = SavedDataType.ZS) {
    val handler = GoldHandler()
    handler.bind(type.getGetter())
    handler.handlerGold(gold)
    handler.save(type.srcPath)
}

fun handleRelics(type: SavedDataType = SavedDataType.ZS) {
    val relicsHandler = RelicsHandler()
    relicsHandler.bind(SaveDataGetter(type))
    relicsHandler.jsonObject.println()

    relicsHandler.handleJSON {
        it.println()
    }

//    relicsHandler.putBuffRelics()
//    relicsHandler.trans(2)
    relicsHandler.addRelics("Dodecahedron", "Tiny Chest", "Bag of Preparation", "White Beast Statue", "Black Star", "Burning Blood", "Vajra", "Oddly Smooth Stone", "Anchor", "Unceasing Top")

    relicsHandler.save(type.srcPath)
}

enum class SavedDataType(val srcPath: String) {
    ZS(zsSrc), DZ(dzSrc), JQR(jqrSrc);

    fun getSrcText(): String {
        val handler = Handler()
        return handler.getDecodeText(srcPath)
    }
}

fun SavedDataType.toJSONObject(): JSONObject {
    return SaveDataGetter(this).jsonObject
}

fun SavedDataType.getGetter(): SaveDataGetter {
    return SaveDataGetter(this)
}

class SaveDataGetter(type: SavedDataType) {

    val jsonObject: JSONObject = JSONObject(type.getSrcText())

}

interface SaveDataHandler {

    var jsonObject: JSONObject

    fun bind(getter: SaveDataGetter) {
        jsonObject = getter.jsonObject
    }

    fun save(path: String) {
        val txt = Handler().encode(jsonObject.toString())
        FileOutputStream(path).bufferedWriter().apply {
            write(txt)
            close()
        }
        println("保存成功")
    }
}

fun SaveDataHandler.save(type: SavedDataType) {
    this.save(type.srcPath)
}

fun SaveDataHandler.bind(type: SavedDataType) {
    this.bind(type.getGetter())
}